package com.yangxiangrice.config.realm;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yangxiangrice.pojo.UserList;
import com.yangxiangrice.service.UserListService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description: TODO
 * @author: shixiaojian
 * @date: 2021年02月23日 14:07
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    UserListService userListService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        String primaryPrincipal = (String) principal.getPrimaryPrincipal();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", primaryPrincipal);
        UserList user = userListService.getOne(wrapper);
        if (!ObjectUtil.isEmpty(user)) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.addRole(user.getUserType().toString());
            return simpleAuthorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", principal);
        UserList user = userListService.getOne(wrapper);
        if (!ObjectUtil.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getPhone(), user.getPasswd(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        }
        return null;
    }
}
